package com.neihe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neihe.common.base.ApiException;
import com.neihe.common.utils.FileUtils;
import com.neihe.entity.File;
import com.neihe.mapper.FileMapper;
import com.neihe.service.IFileService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 物理文件信息表 服务实现类
 * </p>
 *
 * @author neihe
 * @since 2025-01-05
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements IFileService {

    @Override
    public File saveFile(String filename, String realPath, Long totalSize,
                         String identifier, String mimeType, Long userId) {
        return doSaveFile(
                filename,
                realPath,
                totalSize,
                identifier,
                mimeType,
                userId
        );
    }

    @Override
    public List<File> getFileList(Long userId, String identifier) {
        LambdaQueryWrapper<File> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Objects.nonNull(userId), File::getCreateUser, userId);
        queryWrapper.eq(StringUtils.isNotBlank(identifier), File::getIdentifier, identifier);
        return list(queryWrapper);
    }

    /**
     * 保存实体文件记录
     */
    private File doSaveFile(String filename, String realPath, Long totalSize,
                            String identifier, String mimeType, Long userId) {
        File record = assembleFile(filename, realPath, totalSize, identifier, mimeType, userId);
        if (!save(record)) {
            throw new ApiException("内部错误，保存物理文件记录失败");
        }
        return record;
    }

    /**
     * 拼装文件实体对象
     */
    private File assembleFile(String filename, String realPath, Long totalSize,
                              String identifier, String mimeType, Long userId) {
        File record = new File();
        record.setFileId(null);
        record.setFilename(filename);
        record.setRealPath(realPath);
        record.setFileSize(totalSize);
        record.setFileSizeDesc(FileUtils.byteCountToDisplaySize(totalSize));
        record.setFileSuffix(FileUtils.getFileSuffix(filename));
        record.setIdentifier(identifier);
        record.setCreateUser(userId);
        record.setMimeType(mimeType);
        record.setCreateTime(new Date());
        return record;
    }
}
